/**
 * Copyright 2011 Renato de Jesus Manzoni
 * 
 * SED - Software Engineering and Dependability Research Group
 * 
 *     http://www.sed.ic.unicamp.br/
 * 
 * Distributed Systems Laboratory (LSD) in the Institute of Computing (IC) at University of Campinas (UNICAMP)
 * 
 *     http://www.lsd.ic.unicamp.br/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.unicamp.ic.lsd.wscaa.interceptors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;

import br.unicamp.ic.lsd.wscaa.concurrent.ExceptionDispatcher;
import br.unicamp.ic.lsd.wscaa.exception.WSDynamicException;
import br.unicamp.ic.lsd.wscaa.factories.WSExceptionFactory;

/**
 * @author Renato de Jesus Manzoni <rjmanzoni@gmail.com>
 * 
 */
public class WSFaultSoapInterceptor extends AbstractSoapInterceptor {

    private ExceptionDispatcher dispatcher;

    private static Log logger = LogFactory.getLog(WSFaultSoapInterceptor.class);

    /**
     * @param p
     */
    public WSFaultSoapInterceptor() {
	super(Phase.UNMARSHAL);
	getAfter().add(Soap11FaultInInterceptor.class.getName());
    }

    /**
     * @param i
     * @param p
     */
    public WSFaultSoapInterceptor(String i, String p) {
	super(i, p);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.cxf.interceptor.Interceptor#handleMessage(org.apache.cxf.message
     * .Message)
     */

    public void setHandler(ExceptionDispatcher dispatcher) {
	this.dispatcher = dispatcher;
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
	Fault fault = (Fault) message.getContent(Exception.class);
	// TODO pode ser a excecao ou a mensagem dela!

	String exceptionString = fault.getDetail().getFirstChild()
		.getLocalName();

	logger.debug("The exception throwed by the invokation is: "
		+ exceptionString);

	WSDynamicException e = WSExceptionFactory
		.createException(exceptionString);

	if (dispatcher != null)
	    dispatcher.dispatchException(e);
	else
	    logger.debug("There is no handler to this exception: "
		    + exceptionString);
    }

}
